<template>
	<view class="product-info">
		<!-- banner 板块 -->
		<view class="image-swipper-title" style="background: #f5f9bd;">
			<u-swiper :autoplay="false" :list="product.skuImages" height="332" name="imgUrl" @click="showimg"></u-swiper>
		</view>
		
		<!-- 数据板块 -->
		<view class="centent-text">
			<view class="white-box-two">
				<view class="product-title-name">
					{{ product.skuTitle }}
				</view>
				<view class="text-left-right">
					价格：<span style="font-size: 36rpx; font-weight: 500; color: #009B65;">
						¥{{(product.price).toFixed(2)}}
						</span>
				</view>
				<view class="text-left-right">
					库存：{{product.inventory}}
				</view>
				<view class="text-left-right">
					邮费：0
				</view>
				<view class="text-left-right" style="width: 100%; display: flex; flex-direction: row; justify-content: space-between;">
					<text class="tit">购买数量：</text>
					<view class="con">
						<u-number-box :min="1" :max="product.inventory" v-model="buyNum"></u-number-box>
					</view>
				</view>
			</view>

			<view class="white-box-two">
				<!-- 商家信息 -->
				<view class="botent-titel-box">
					商家信息
				</view>
				<view class="text-left-right">
					商家：{{product.shop.shopName}}
				</view>
				<view class="text-left-right">
					商家电话：{{shopPhone.answer}}
				</view>
				<view class="text-left-right">
					配送电话：{{shopPhone.inform.length == 0?'暂无绑定':shopPhone.inform[0]}}
				</view>			
				<view class="text-left-right">
					商家地址：{{product.shop.receiveAddress}}
				</view>
				
				<view class="botent-titel-box" style="margin-top: 60rpx;">
					买家收货信息
				</view>
				<!-- 买家收货信息 -->
				<view class="text-left-right" style="display: flex; margin-top: 20rpx;">
					收货人：
					<input class="uni-input"  @input="changeName" v-model="userName"
						placeholder-style="color: red;"
						border="none" placeholder="请输入预约人"></input>
				</view>
				<view class="text-left-right" style="display: flex;">
					手机号：
					<input class="uni-input" type="number" @input="changePhone" maxlength="11" v-model="userPhone"
					placeholder-style="color: red;"
						border="none" placeholder="请输入手机号"></input>
				</view>
				<view class="text-left-right" style="display: flex; ">
					收货人地址：<textarea v-model="receiverDetailAddress" style="width: 480rpx; height: 120rpx;" placeholder-style="font-weight: 100; width: 540rpx !important; color: red;" placeholder="请填入您在农博园内具体位置" />
				</view>
				<view class="text-left-right" style="display: flex; ">
					备注：<textarea v-model="note" style="width: 480rpx; height: 120rpx;" placeholder-style="font-weight: 100; width: 580rpx !important" placeholder="给商家留言,不超过100字" />
				</view>
			</view>

			
		</view>
		
		<!-- 商品详情 -->
		<view class="detail-desc">
			<view class="d-header">
				<text>商品详情</text>
			</view>
			<view v-if="product.spuInfoDesc">
				<u-parse class="showInfoText" :html="product.spuInfoDesc.decript"></u-parse>
			</view>
		</view>
		
		
		<view class="promptly-buy">
			<view class="money-text">
				共{{buyNum}}件，合计：<span class="money-number">￥{{(product.price * buyNum).toFixed(2)}}</span>
			</view>
			<view class="buy-bottom" @click.stop="buySubmit" v-if="!isPay">
				立即支付
			</view>
			<view class="buy-bottom" v-else @click.stop="showMyOrder">
				查看订单
			</view>
		</view>
		
	</view>
</template>

<script>
	import dragButton from "@/components/drag-button/drag-button.vue";
	import uniPopup from "@/components/uni-popup/uni-popup.vue"
	import AiProgress from "@/components/ai-progress/ai-progress.vue"
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		components: {
			uniPopup,
			dragButton,
			AiProgress
		},
		data() {
			return {
				x: 0,
				y: 0,
				old: {
					x: 0,
					y: 0
				},
				// 节流控制
				flag: true,
				// 是否已经支付
				isPay: false,
				userName: '',
				userPhone: '',
				countDateTime: {
					countDay: 0,
					countHour: 0,
					countDown: 0,
					secondTime: 10,
				},
				note: "",
				receiverDetailAddress: "",
				skuNumber: {},
				showDown: true,
				showImageStatus: false,
				ImageList: [],
				titleHeight: '',
				skuId: '',
				unit: 1,
				showCoupon: false,
				coupons: [],
				product: {
					skuImages: [{}],
					productMainImage: {},
					spuAttrValues: [],
					shop: {},
					saleAttrValue: {},
					saleAttrValues: []
				},
				shopPhone: {
					answer: null,
					inform: null
				},
				// 购买数量
				buyNum: 1,
				// 购物车商品种类数量
				cartNum: 0,
				// 是否收藏商品
				isCollected: false,
				specClass: 'none',
				type: '',
				// 评论列表
				commentList: [],
				// 总评论数
				totalComment: 0,
				// 评论的用户评分
				stars: [0, 0, 0, 0, 0]
			};
		},
		onLoad(options) {
			console.log("进入了页面");
			this.getPhoneHeightStatus()
			this.skuId = options.id;
			// 已抢多少
			if (this.hasLogin) {
				// 检查商品是否被收藏
				this.checkCollected(this.skuId);
				// 获取购物车商品数量
				this.inquiryCartNum();
			}
		},
		onShow() {
			this.getSkuInfo();
		},
		computed: {
			...mapState(['hasLogin', 'userInfo']),
		},
		onShareAppMessage(res) {
			return this.shareCoupon(this.skuId, this.product.skuSwiperImg)
		},
		methods: {
			...mapMutations(['login', 'addFootPrint']),
			
			// 去分享
			shareCoupon(skuId, skuSwiperImg) {
				this.skuId = skuId
				this.product.skuSwiperImg = skuSwiperImg
				console.log(skuId);
				return {
					title: '活动大降价',
					imageUrl: skuSwiperImg,
					path: '/pages/sys/home/product?id=' + skuId
				}
			},
			
			// 获取店家手机号和配送员电话
			getShopPhone(shopId){
				this.$api.request.getShopPhone({
					shopId: shopId
				}, res => {
					if(res.code == 200){
						this.shopPhone = res.data
					}
				})
			},
			
			// 获取用户输入手机号
			changePhone(e) {
				this.userPhone = e.target.value
			},
			changeName(e) {
				this.userName = e.target.value
			},
			
			// 倒计时到点触发
			timeout(){
				const that =this
				// 1、禁用按钮
				console.log("倒计时结束");
				// 2、显示弹窗
				uni.showModal({
					title: '温馨提示',
					content: '本次活动已结束，敬请等待下次促销活动',
					showCancel: false,
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
							uni.navigateBack({
								delta: 1
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			
			onChange: function(e) {
				this.old.x = e.detail.x
				this.old.y = e.detail.y
			},
	
			// 获取导航栏的高度
			/**
			 * 获取手机状态栏高度
			 */
			getPhoneHeightStatus() {
				let systemInfo = uni.getSystemInfoSync();
				let pxToRpxScale = 750 / systemInfo.windowWidth; //px转换到rpx的比例
				let fontSize = systemInfo.fontSizeSetting * pxToRpxScale; // 用户设置的字体大小
				let statuHeight = systemInfo.statusBarHeight * pxToRpxScale; //状态栏的高度
				let titleHeight = 25 * pxToRpxScale; //导航栏高度，这个一般是固定的
				// console.log(titleHeight);
				this.titleHeight = titleHeight
			},
			// 返回上一级页面
			backPage() {
				uni.navigateBack({
					delta: 1
				})
			},
	
	
			togglePopup(type, open) {
				switch (type) {
					case 'top':
						this.content = '顶部弹出 popup'
						break
	
					case 'bottom':
						this.content = '底部弹出 popup'
						break
					case 'center':
						this.content = '居中弹出 popup'
						break
				}
				this.type = type
				this.$nextTick(() => {
					this.$refs['show' + open].open()
				})
			},
			closeAttr() {
				this.$refs.showattr.close();
			},
			// 是否已收藏商品
			checkCollected(skuId) {
				this.$api.request.skuIsCollected({
					skuId: skuId
				}, res => this.isCollected = res.data);
			},
			// 查询购物车商品数量
			inquiryCartNum() {
				try {
					this.$api.request.getCartNum(res => this.cartNum = res.data);
				} catch (e) {
					console.log(e);
				}
			},
			getSkuInfo() {
				try {
					this.$api.request.skuDetail({
						id: this.skuId
					}, res => {
						this.product = res.data
						this.getShopPhone(res.data.shop.id)
						// 商品处于活动中，查询活动结束倒计时
						// if(res.data.spuInfo.isActivityStatus == '1'){
						// 	that.$api.request.getSpuCountDown({
						// 		actId: res.data.spuInfo.actId
						// 	}, rs => {
						// 		if(rs.code == 200){
						// 			this.countDateTime = rs.data
						// 		}
						// 	})
						// }
						// 商品是否处于拼团中，查询拼团结束倒计时
						if(res.data.spuInfo.spuAddType == 1){
							// 已经抢购了多少
							this.getSkuNumInfo(res.data.skuId)
							// 活动倒计时
							this.$api.request.getGroupCountDown({
								skuId: res.data.skuId
							}, rs => {
								if(rs.code == 200){
									this.countDateTime = rs.data
								}
							})
						}
					});
				} catch (e) {
					console.log(e);
				}
			},
			// 获取商品已抢进度
			getSkuNumInfo(skuId){
				this.$api.request.getSkuNumInfo({
					skuId: skuId
				}, resp => {
					if(resp.code == 200){
						this.skuNumber = resp.data
					}
				})
			},
			// 查询商品评论
			searchProductComment(id) {
				let postData = {
					keyArray: ['PRODUCTUUID'],
					productUuid: id,
					startIndex: 0,
					pageSize: 1
				}
				this.$api.request.goodsComment(postData, res => {
					if (res.body.status.statusCode === '0') {
						this.commentList = res.body.data.commentList;
						this.totalComment = res.body.data.total;
					} else {
						console.log(res.body.status.errorDesc);
					}
				});
			},
			//规格弹窗开关
			toggleSpec() {
				if (this.specClass === 'show') {
					this.specClass = 'hide';
					setTimeout(() => {
						this.specClass = 'none';
					}, 250);
				} else if (this.specClass === 'none') {
					this.specClass = 'show';
				}
			},
			//选择规格
			selectAttrValue(attrValue) {
				if (this.skuId != attrValue) {
					this.navTo('/pages/sys/home/product?id=' + attrValue.skuId);
				}
			},
			numberChange(e) {
				this.unit = e.number;
			},
			// 登录
			goLogin(){
				uni.navigateTo({
					url: '/pages/sys/common/login'
				})
			},
			//分享
			// share() {
			//   this.$refs.share.toggleMask();
			// },
			// 收藏（取消收藏）商品
			toFavorite() {
				const that = this
				if(!this.hasLogin){
					this.goLogin()					
				}else{
					this.$api.request.skuCollect({
						skuId: this.skuId,
						spuId: this.product.spuId,
						spuName: this.product.spuInfo.spuName,
						spuImage: this.product.skuDefaultImg,
						price: this.product.price
					}, res => {
						this.$u.toast(res.message);
					})
					this.isCollected = !this.isCollected;
				}
				
			},
			// 立即购买
			buySubmit() {
				if(!this.hasLogin){
					this.goLogin()					
				}else{
					if(this.product.inventory <= 0){
						uni.showModal({
							title: '温馨提示',
							content: '库存不足，无法购买',
							showCancel: false,
							success:res => {
								// 点击拨打电话
								if(res.confirm){
									
								}
							}
						})
					}else {
						if(this.product.skuType == 1){
							let sku = {
								skuData: this.product,
								buyNum: this.buyNum
							};
							uni.setStorageSync("placeOrder", JSON.stringify(sku));
							this.navTo("/pages/sys/shopCart/placeOrder");
						}else {
							// 判断库存是否为零
							if(this.product.inventory == 0){
								uni.showModal({
									title: '温馨提示',
									content: '库存不足，无法购买',
									confirmText: '联系店家',
									cancelText: '我再想想',
									success:res => {
										// 点击拨打电话
										if(res.confirm){
											uni.makePhoneCall({
												phoneNumber: this.shopPhone.answer
											})
										}
									}
								})
							}else{
								// 店铺营业状态
								this.$api.request.getShopOnlineStatus({
									shopId: this.product.shop.id
								}, result => {
									if(result.code == 200){
										if(result.data.onlineStatus == '1'){
											// 跳转至服务页面
											// uni.navigateTo({
											// 	url: '/pagesA/appointment/service/reserve?id=' + this.product.skuId
											// })
											
											if (this.userPhone == null || this.userPhone.length != 11) {
												uni.showModal({
													title: '温馨提示',
													content: '请输入正确的手机号',
													showCancel: false
												})
											}else if(this.userName == null || this.userName == ""){
												uni.showModal({
													title: '温馨提示',
													content: '请填写收货姓名',
													showCancel: false
												})
											}else {
												// 节流控制
												if(this.flag){
													this.flag = false
													let skuList = []
													skuList.push(this.product)
													skuList[0].quantity = this.buyNum
													let data = skuList
													delete data[0].shop.createTime
													this.$api.request.isEnoughStatus(data, res => {
														if(res.code == 200 && res.data == true){
															// 下单购买
															let param = {
																totalAmount: this.product.price * this.buyNum,
																payAmount: this.product.price * this.buyNum,
																integration: this.product.price * this.buyNum,
																growth: this.product.price * this.buyNum,
																shopId: this.product.shop.id,
																receiverName: this.userName || this.userInfo.nickname,
																receiverPhone: this.userPhone,
																receiverDetailAddress: this.receiverDetailAddress,
																note: this.note,
																sourceType: 1,
																orderType: "2",
																deliveryCompany: '普通配送',
																billType: 0,
																useIntegration: 0,
																integrationAmount: 0,
																couponId: null,
																couponAmount: null,
																itemList: [{
																	spuId: this.product.spuId,
																	spuName: this.product.spuInfo.spuName,
																	spuPic: this.product.spuImages.length > 0 ? this.product.spuImages[0] :'',
																	spuBrand: this.product.brandName,
																	categoryId: this.product.catalogId,
																	skuId: this.product.skuId,
																	skuRebate: this.product.skuRebate,
																	skuName: this.product.skuName,
																	skuPic: this.product.skuImages[0].imgUrl,
																	skuPrice: this.product.price,
																	skuQuantity: this.buyNum,
																	shopId: this.product.shop.id,
																	actId: this.product.spuInfo.actId,
																	promotionAmount: this.product.price * this.buyNum,
																	integrationAmount: 0,
																	realAmount: 0,
																	couponAmount: 0
																}]
															}
															
															console.log(param);
															
															try {
																this.$api.request.memberSubmitOrder(param, res => {
																	res.data.user.number = this.buyNum
																	this.toPay(res);
																})
															} catch (e) {
																console.log(e);
															}
														}else{
															setTimeout(() => {
																this.$api.msg("库存不足")
																setTimeout(() => {
																	this.getSkuInfo();
																	this.buyNum = 1
																}, 2000)
															}, 1000)
														}
													})
													
													setTimeout(() => {
														this.flag = true						
													},3000)
												}
												
											}
											
										}else {
											uni.showToast({
												title: '该店铺暂停营业中，无法购买',
												icon: 'none'
											})
										}
									}
								})
							}
						}
					}
					
				}
				
			},
			// 谈起支付框
			toPay(data) {
				const that = this
				let res = JSON.parse(data.data.jsonStr)
				console.log(data);
				uni.requestPayment({
					timeStamp: res.timeStamp,
					nonceStr: res.nonceStr,
					package: res.package,
					signType: res.signType,
					paySign: res.paySign,
					success: (res) => {
						console.log("成功", res);
						this.$api.request.payNotify(data.data.user, res => {
							console.log("通知", res);							
							
							uni.showModal({
								title: '温馨提示',
								content: '电话通知商家快速备餐！\r\n 我的订单里可查询送货员电话',
								confirmText: '拨打电话' + this.shopPhone.answer,
								showCancel: false,
								success:(res) => {
									if(res.confirm){
										uni.makePhoneCall({
											phoneNumber: this.shopPhone.answer
										})
										that.isPay = true
									}
								}
							})
						})
			
					},
					fail: (err) => {
						console.log(err);
						this.$api.request.addOrderMessageQueue({orderId: data.data.user.id}, res => {
							console.log(res);
							if(res.code == 200){
								uni.navigateTo({
									url: '/pagesA/sys/user/order?type=0'
								});
							}
						})
					}
				})
			},
			// 查看我的订单
			showMyOrder(){
				uni.redirectTo({
					url: "/pagesA/sys/user/order?type=2"
				})
			},
			// 添加商品到购物车
			addCart() {
				// 判断库存
				if(this.product.inventory > 0 && this.product.spuAddType != 1){
					if(!this.hasLogin){
						this.goLogin()						
					}else{
						// 组装销售属性
						let attr = [];
						for (var i = 0; i < this.product.saleAttrValues.length; i++) {
							for (var j = 0; j < this.product.saleAttrValues[i].value.length; j++) {
								let item = this.product.saleAttrValues[i].value[j];
								if (this.skuId == item.skuId) {
									attr.push({
										key: this.product.saleAttrValues[i].key,
										value: item.attrValue
									});
									break;
								}
							}
						}
						this.$api.request.addShopCart({
							quantity: this.buyNum,
							shopId: this.product.shopId,
							productSpuId: this.product.spuId,
							productSkuId: this.product.skuId,
							price: this.product.price,
							productPic: this.product.skuDefaultImg,
							productName: this.product.skuName,
							productSubTitle: this.product.skuSubtitle,
							productCategoryId: this.product.catalogId,
							productBrand: this.product.brandName,
							productAttr: JSON.stringify(attr)
						}, res => {
							this.$u.toast("添加成功");
							this.inquiryCartNum();
							this.toggleSpec();
						})
					}	
				}else{
						uni.showModal({
							title: '温馨提示',
							content: '库存不足，无法收藏',
							showCancel: false,
							success:res => {
								// 点击拨打电话
								if(res.confirm){
									
								}
							}
						})
					}
			},
			navTo(url) {
				uni.navigateTo({
					url: url
				})
			},
			previewImage(url) {
				var urls = [];
				urls.push(url);
				uni.previewImage({
					current: url,
					indicator: "number",
					loop: "true",
					urls: urls
				})
			},
			//搜索优惠券
			searchCoupon() {
				let postData = {
					keyArray: ['ACTIVE', 'PRODUCT', 'MERCHANT'],
					productUuid: this.id,
					merchantUuid: this.product.merchantDTO.merchantUuid,
					active: true,
					startIndex: 0,
					pageSize: 100
				};
				this.$api.request.couponList(postData, res => {
					if (res.body.status.statusCode === '0') {
						var coupons = res.body.data.coupons;
						this.coupons = coupons
					}
				}, true);
			},
			//领取优惠券
			getCoupon(item) {
				this.$api.request.getCoupon({
					actionType: 'RECEIVE',
					couponDTO: {
						couponUuid: item.couponUuid,
					},
					userDTO: {
						userUuid: this.userInfo.userUuid
					},
					receiveChannel: 'SELF'
				}, res => {
					if (res.body.status.statusCode === '0') {
						this.$api.msg('领取成功');
					} else {
						this.$api.msg(res.body.status.errorDesc);
					}
				}, false);
			},
			stopPrevent() {},
			// 查看图片
			showimg(index){
				console.log(this.product.skuImages[index].imgUrl);
				// 预览图片
				let urls = [this.product.skuImages[index].imgUrl]
				uni.previewImage({
					urls: urls,
					longPressActions: {
						itemList: [ '保存图片'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
		},
	
	}
</script>

<style lang="scss">
	.product-info{
		width: 100vw;
		// background: linear-gradient(360deg, #FFFFFF 0%, #E9FFF8 40%, #C7FFEC 100%);
		background: #f5f9bd;
	}
	
	.image-swipper-title{
		padding: 24rpx;
	}
	
	.centent-text {
		width: auto;
		margin: 20rpx 30rpx; 
		display: flex;
		flex-direction: column;
		// border-top: 1rpx solid #ceccca;
	}
	
	
	.product-title-name{ 
		font-size: 36rpx;
		font-weight: bold;
		color: #111111;
		margin-top: 10rpx;
		margin-bottom: 20rpx;
		font-family: PingFangSC-Medium, PingFang SC;
	}
	
	.text-left-right{
		color: gray;
		font-size: 30rpx;
		margin-bottom: 10rpx;
	}
	
	/*  详情 */
	.detail-desc {
		background: #edf4b8;
		margin-top: 16rpx;
		padding-bottom: 180rpx;
	
		.d-header {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 80rpx;
			font-size: $font-base + 2upx;
			color: $font-color-dark;
			position: relative;
	
			text {
				padding: 0 20rpx;
				background: #fff;
				position: relative;
				z-index: 1;
			}
	
			&:after {
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translateX(-50%);
				width: 300rpx;
				height: 0;
				content: '';
				border-bottom: 1px solid #ccc;
			}
		}
	}
	
	.promptly-buy{
		width: auto;
		height: 130rpx;
		padding: 0 20rpx;
		display: flex;
		align-items: center;
		flex-direction: row;
		background: #FFFFFF;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 9999999;
	}
	
	.money-text{
		font-size: 30rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #111111;
		line-height: 40rpx;
	}
	
	.money-number{
		font-size: 34rpx;
		font-family: DINAlternate-Bold, DINAlternate;
		font-weight: bold;
		color: #009B65;
		line-height: 36rpx;
	}
	
	.buy-bottom{
		width: 300rpx;
		height: 80rpx;
		background: linear-gradient(328deg, #03D289 0%, #009B65 100%);
		border-radius: 46rpx;
		font-size: 42rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #FFFFFF;
		line-height: 44rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-left: 40rpx;
	}
	
	.white-box-two{
		width: auto;
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 20rpx 20rpx;
		margin-bottom: 30rpx;
	}
	
	.botent-titel-box{
		width: 60%;
		height: 50rpx;
		font-size: 36rpx;
		line-height: 50rpx;
		text-align: center;
		margin: 0 auto;
		background: #4b9556;
		letter-spacing: 4rpx;
		color: #edf4b8;
		border-radius: 50rpx;
		margin-bottom: 10rpx;
	}
</style>